package com.example.demo.service;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.stereotype.Service;

@Service
public class OrderService {

    private int failureCount = 0;
    private int requestCount = 0;


    
    // 使用断路器保护方法
    @CircuitBreaker(name = "backendA", fallbackMethod = "getDefaultOrder")
    public Object getOrder(String orderId) {
        // 调用远程服务
//        simulateFailure();
        if (orderId.equals("1")) {
            throw new RuntimeException("服务暂时不可用");
        }
        System.out.println("222");
//        System.out.println("订单正常 订单ID: " + orderId);
       return "sucess";
    }
    
    // 降级方法（参数必须一致，可添加Throwable参数）
    private Object getDefaultOrder(String orderId,Throwable t) {
        System.out.println("服务降级，订单ID: " + orderId);
        System.out.println(t);
        return "fail";
    }

    // 模拟服务故障
    private void simulateFailure() {
        requestCount++;
        if (requestCount % 3 == 0) { // 每3次请求失败1次
            System.out.println("模拟服务调用失败");
            throw new RuntimeException("服务暂时不可用");
        }
    }
}
